#include <errno.h>
#include <stdio.h>
#include <unistd.h>

#include <arpa/inet.h>

#include <netinet/in.h>
#include <netinet/ip.h>

#include <sys/socket.h>
#include <sys/types.h>

#include "protocol.h"

int main (int argc, char *argv[])
{
    char buf[BUFSIZE];
    int fd, acp_fd;
    int ret = 0;
    int opt = 1;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        perror("socket");
        ret = errno;
        goto e_socket;
    }

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    if (bind(fd, (struct sockaddr *) &server_addr, sizeof(server_addr)))
    {
        perror("bind");
        goto e_bind;
    }

    if (listen(fd, 1))
    {
        perror("listen");
        goto e_listen;
    }

    while (1)
    {
        acp_fd = accept(fd, (struct sockaddr *) &client_addr, &client_addr_len);
        if (acp_fd < 0)
        {
            perror("accept");
            break;
        }
        while (recv(acp_fd, buf, BUFSIZE, 0) > 0)
        {
            printf("%s", buf);
            fflush(stdout);
        }
        close(acp_fd);
    }

  e_listen:
  e_bind:
    close(fd);
  e_socket:
    return ret;
}

